<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace api\portal\controller;
use cmf\controller\RestBaseController;

use think\Db;

use app\portal\model\HouseFieldType;
use app\portal\model\House;
use app\portal\model\UserFavoriteModel;
use app\portal\model\UserHousePasswordModel;
use app\portal\model\HouseRecord;

use api\portal\service\HouseService;

class HouseController extends RestBaseController
{

    public function index () {
      if (empty($this->user)) {
        unauthorized();
      }
      $data = [
        'filter' => $this->filter(),
      ];
      return $this->success('success', $data);
    }

    public function list ()
    {
      $params = $this->request->param();
      return HouseService::listData($params);
    }

    public function collection() {
      return HouseService::listData($params);
    }

    public function shoufang() {
    }

    public function notice() {
      $data = Db::name('gonggao')->field('id, title')->limit(10)->orderRaw('id desc')->select();
      return $data;
    }

    public function single() {
      if (empty($this->user)) {
        unauthorized();
      }
      $param = $this->request->param();
      if (!isset($param['id']) || intval($param['id']) == 0) {
        $this->error('参数不正确！');
      }

      // 更新浏览次数
      $res = HouseService::add_count($param['id'], 'view');
      if (!$res) {
        $this->error('统计错误');
      }

      $info = House::find($param['id']);

      // 获取参数
      $fieldIds = [];
      $fieldIds[$info->structure_type] = $info->structure_type;
      $fieldIds[$info->decoration_type] = $info->decoration_type;
      $fieldIds[$info->direction] = $info->direction;
      $fieldIds[$info->floor_type] = $info->floor_type;
      $fieldIds[$info->purpose] = $info->purpose;
      $fieldIds[$info->tax_bear_type] = $info->tax_bear_type;

      $paramsData = HouseFieldType::whereIn('id', $fieldIds)->select();
      $params = [];
      foreach ($paramsData as $key => $value) {
        $params[$value->id] = $value->name;
      }

      // 判断是否收藏
      $user_favorite = Db::name('user_favorite')->where([
          'user_id' => $this->user['id'],
          'object_id' => $param['id'],
          'table_name' => 'houses',
        ])->find();
      if (isset($user_favorite['id'])) {
        $info['favorite'] = true;
      } else {
        $info['favorite'] = false;
      }

      return [
        'info' => $info,
        'data' => $info->profile,
        'params' => $params,
      ];
    }

    public function favorite() {
      if (empty($this->user)) {
        unauthorized();
      }

      $userId = $this->user['id'];

      $param = $this->request->param();
      if (isset($param['id']) && intval($param['id']) > 0) {
        $get = Db::name('user_favorite')->where([
            'user_id' => $userId,
            'object_id' => $param['id'],
            'table_name' => 'houses',
          ])->find();

        if (isset($get['id'])) {
          Db::name('user_favorite')->delete($get['id']);
          HouseService::add_count($param['id'], 'collection', 'reduce');
          $this->success('取消收藏成功');
        } else {
          HouseService::add_count($param['id'], 'collection');
          Db::name('user_favorite')->insert([
            'user_id' => $userId,
            'object_id' => $param['id'],
            'table_name' => 'houses',
          ]);

          $this->success('收藏成功');
        }
      } else {
        $this->error('error');
      }
    }

    public function show_password() {
      if (empty($this->user)) {
        unauthorized();
      }

      $userId = $this->user['id'];

      $param = $this->request->param();
      if (isset($param['id']) || !empty($param['id'])) {
        // 记录
        $record = new HouseRecord;
        $record->addRecord($param['id'], $this->user['id'], $this->user['user_nickname'], 'unlock');
        HouseService::add_count($param['id'], 'unlock');

        $data = Db::name('user_house_password')->where('house_id', $param['id'])->where('user_id', $this->user['id'])->find();

        $password = '';
        if (empty($data)) {
          $housePassword = Db::name('house_password')->where('house_id', $param['id'])->orderRaw('rand()')->find();
          if (empty($housePassword)) {
            $this->error('该房源暂无密码');
          } else {
            $password = $housePassword['password'];
            Db::name('user_house_password')->insert([
              'user_id' => $userId,
              'house_id' => $param['id'],
              'password' => $password,
            ]);
          }
        } else {
          $password = $data['password'];
        }

        $this->success('success', $password);
      }
    }

    public function reset_password() {
      if (empty($this->user)) {
        unauthorized();
      }

      $userId = $this->user['id'];

      $param = $this->request->param();

      if (!isset($param['id']) || empty($param['id'])) {
        $this->error('参数不正确！');
      }

      $housePassword = Db::name('house_password')
        ->where('house_id', $param['id'])
        ->where('password', '<>', $param['password'])
        ->orderRaw('rand()')
        ->find(); // 随机获取密码
      if (empty($housePassword)) {
        $this->error('该房源暂无密码');
      } else {
        $password = $housePassword['password'];
        Db::name('user_house_password')->where('house_id', $param['id'])
          ->where('user_id', $userId)
          ->update([
            'password' => $password,
          ]);

        $this->success('success', $password);
      }
    }

    private function filter() {
      // 区域
      $region = HouseFieldType::field(['id'=>'value', 'name'])->where('catid', 7)->select();

      // 户型
      $structure_type = HouseFieldType::field(['id'=>'value', 'name'])->where('catid', 1)->select();
      // 面积
      $area = [
        ['name' => '小于40', 'value' => 'lower-40'],
        ['name' => '40-60', 'value' => '40-60'],
        ['name' => '60-80', 'value' => '60-80'],
        ['name' => '80-100', 'value' => '80-100'],
        ['name' => '100-120', 'value' => '100-120'],
        ['name' => '120以上', 'value' => 'higher-120'],
      ];
      $huxing = [
        ['title' => '', 'field' => 'structure_type', 'data' => $structure_type],
        ['title' => '面积', 'field' => 'area', 'data' => $area],
      ];

      // 价格
      $price = [
        ['name' => '50万以下', 'value' => 'lower-50'],
        ['name' => '50-60万', 'value' => '50-60'],
        ['name' => '61-70万', 'value' => '61-70'],
      ];

      // 更多
      $direction = HouseFieldType::field(['id'=>'value', 'name'])->where('catid', 4)->select(); // 朝向
      $decoration = HouseFieldType::field(['id'=>'value', 'name'])->where('catid', 2)->select(); // 装修类型
      $floor = [
        ['name' => '顶层', 'value' => 'top'],
        ['name' => '中间层', 'value' => 'center'],
        ['name' => '底层', 'value' => 'bottom'],
      ];

      // 状态
      $status = [];
      $house = new House;
      $sellTypes = $house->sellTypes;
      foreach ($sellTypes as $key => $value) {
        $status[] = ['name' => $value, 'value' => $key];
      }

      $more = [
        ['title' => '状态', 'field' => 'sell_type', 'data' => $status],
        ['title' => '房源类型', 'field' => 'house_type', 'data' => [
          [ 'name' => '优居房源', 'value' => 1],
          [ 'name' => '美化房源', 'value' => 0],
          [ 'name' => '非美化房源', 'value' => 2],
        ]],
        ['title' => '朝向', 'field' => 'direction', 'data' => $direction],
        ['title' => '装修', 'field' => 'decoration_type', 'data' => $decoration],
        ['title' => '楼层', 'field' => 'floor', 'data' => $floor],
      ];

      $data = [
        ['field' => 'region', 'name' => '区域', 'data' => $region],
        ['field' => 'huxing', 'name' => '户型', 'data' => $huxing],
        ['field' => 'price', 'name' => '价格', 'data' => $price],
        ['field' => 'more', 'name' => '更多', 'data' => $more],
      ];

      return $data;
    }

    public function favorite_index() {
      if (empty($this->user)) {
        unauthorized();
      }

      // 参数获取
      $fieldData = Db::name('house_field_types')->where('catid', 1)->select();
      $fields = [];
      foreach ($fieldData as $key => $value) {
        $fields[$value['id']] = $value['name'];
      }

      $list = UserFavoriteModel::with('house')->where([
        'user_id' => $this->user['id'],
      ])->limit(20)->orderRaw('id desc')->select();

      return [
        'fields' => $fields,
        'list' => $list,
      ];
    }

    public function favorite_list() {
      if (empty($this->user)) {
        unauthorized();
      }
      $param = $this->request->param();

      $model = UserFavoriteModel::with('house');
      if (isset($param['lastid']) && intval($param['lastid']) > 0) {
        $model->where('id', '<', $param['lastid']);
      }

      return $model->where([
        'user_id' => $this->user['id'],
      ])->limit(20)->orderRaw('id desc')->select();
    }

    public function lock_index() {
      if (empty($this->user)) {
        unauthorized();
      }

      // 参数获取
      $fieldData = Db::name('house_field_types')->where('catid', 1)->select();
      $fields = [];
      foreach ($fieldData as $key => $value) {
        $fields[$value['id']] = $value['name'];
      }

      $list = UserHousePasswordModel::with('house')->where([
        'user_id' => $this->user['id'],
      ])->limit(20)->orderRaw('id desc')->select();

      return [
        'fields' => $fields,
        'list' => $list,
      ];
    }

    public function lock_list() {
      if (empty($this->user)) {
        unauthorized();
      }
      $param = $this->request->param();

      $model = UserHousePasswordModel::with('house');
      if (isset($param['lastid']) && intval($param['lastid']) > 0) {
        $model->where('id', '<', $param['lastid']);
      }

      return $model->where([
        'user_id' => $this->user['id'],
      ])->limit(20)->orderRaw('id desc')->select();
    }

    public function get_tel() {
      $param = $this->request->param();
      if (!isset($param['id']) || intval($param['id']) == 0) {
        $this->error('参数不正确');
      }
      $id = $param['id'];

      $record = new HouseRecord;
      $record->addRecord($id, $this->user['id'], $this->user['user_nickname'], 'connect');

      $res = HouseService::add_count($id, 'connect');

      if ($res) {
        $this->success('获取成功');
      } else {
        $this->error('获取失败');
      }
    }

}
